package no.rodland.acc.action;

import no.rodland.acc.chart.Element;
import no.rodland.acc.chart.Tooltip;
import no.rodland.acc.chart.X_Axis;
import no.rodland.acc.chart.Y_Axis;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import no.rodland.acc.db.DbRow;
import no.rodland.acc.db.DbService;

import org.apache.struts2.json.annotations.JSON;
import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.List;

public class ChartAction extends ActionSupport {
    private final DbService service;

    private List<Element> elements = new ArrayList<Element>();
    private Y_Axis yAxis = new Y_Axis();
    private X_Axis xAxis = new X_Axis();
    private static final int DAYS = 31;
    private Tooltip tooltip = new Tooltip();
    private String bgColour = "#F0F0F0";

    public ChartAction(DbService service) {
        this.service = service;
    }

    @JSON(name = "bg_colour")
    public String getBgColour() {
        return bgColour;
    }

    @JSON(name = "bg_colour")
    public void setBgColour(String bgColour) {
        this.bgColour = bgColour;
    }

    public Tooltip getTooltip() {
        return tooltip;
    }

    public void setTooltip(Tooltip tooltip) {
        this.tooltip = tooltip;
    }

    @Override
    public String execute() throws Exception {
        elements.clear();

        List<DbRow> stats = null;
        //stats = service.getData(DAYS);
        fillElements(stats);
        return Action.SUCCESS;
    }

    private void fillElements(List<DbRow> rows) {
        int currentCampaign = 0;
        Element currentElement = null;
        double maxRevenue = 0;

        // loop over dataset
        for (DbRow row : rows) {
            if (row.getId() != currentCampaign) {
                currentCampaign = row.getId();
                currentElement = new Element(DAYS);
                elements.add(currentElement);
            }
            double value = 10;
            if (value > maxRevenue) {
                maxRevenue = value;
            }

            currentElement.addData(new DateTime(row.getDate()), value, row);
        }
        xAxis.setDates(DAYS);
        yAxis.setMax(maxRevenue);
    }

    public List<Element> getElements() {
        return elements;
    }

    public void setElements(List<Element> elements) {
        this.elements = elements;
    }

    @JSON(name = "y_axis")
    public Y_Axis getyAxis() {
        return yAxis;
    }

    @JSON(name = "y_axis")
    public void setyAxis(Y_Axis yAxis) {
        this.yAxis = yAxis;
    }

    @JSON(name = "x_axis")
    public X_Axis getxAxis() {
        return xAxis;
    }

    @JSON(name = "x_axis")
    public void setxAxis(X_Axis xAxis) {
        this.xAxis = xAxis;
    }
}
